package com.it.water.controller.MessageController;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class AudioController {

    @PostMapping("/receiveMessage")
    public ResponseEntity<String> receiveMessage(@RequestBody String message) {
        // 处理接收到的消息
        System.out.println("Received message from Python: " + message);
        // 返回响应
        return ResponseEntity.ok("Message received");
    }

    @GetMapping("/sendAudio")
    public ResponseEntity<byte[]> sendAudio() {
        // 从某个地方获取音频数据，这里假设 audioData 是音频文件的字节数组
        byte[] audioData = getAudioData();

        // 设置响应头，告诉客户端返回的是音频数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(audioData.length);
        headers.setContentDispositionFormData("attachment", "audio.wav");

        // 返回音频数据
        return new ResponseEntity<>(audioData, headers, HttpStatus.OK);
    }

    private byte[] getAudioData() {
        // 从某个地方获取音频数据的逻辑
        // 这里可以是读取文件、从数据库中获取等
        // 这里只是一个简单的示例，实际情况可能更复杂
        // 假设这里返回的是音频文件的字节数组
        // 从文件中读取音频数据
            try {
                File audioFile = new File("path/to/audio.wav");//填写音频文件路径
                FileInputStream fileInputStream = new FileInputStream(audioFile);
                byte[] audioData = new byte[(int) audioFile.length()];
                fileInputStream.read(audioData);
                fileInputStream.close();
                    return audioData;
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }
}
